package com.bilibili.movies.util;

import com.bilibili.movies.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private final static String code="CPY";
    private final static Long expiration= 43200000L;
    public static String setJWT(User user){
        Map<String,Object> claims=new HashMap<>();
        if(user.getAvatar()!=null){
            claims.put("avatar",user.getAvatar());
        }
        if(user.getController()!=null){
            claims.put("controller",user.getController());
        }
        if(user.getNickName()!=null){
            claims.put("nickName",user.getNickName());
        }

        claims.put("email",user.getEmail());
        claims.put("id",user.getId());
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,code.getBytes(StandardCharsets.UTF_8))
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .compact();
    }
    public static Claims judge(String jwt){
        Claims claims=Jwts.parser()
                .setSigningKey(JWTUtils.code.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }
}
